import axios from "axios";
import { Notification, MessageBox, Message } from "element-ui";
import router from "@/router";

axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
// 创建axios实例
const service = axios.create({
  baseURL: "https://www.xjwd.net:9500",
  timeout: 30000,
});

// 添加全局变量标记是否正在处理401
let isHandling401 = false;

// request拦截器
service.interceptors.request.use(
  (config) => {
    const getToken = localStorage.getItem("token");
    if (getToken) {
      config.headers["Authorization"] = getToken;
    }
    return config;
  },
  (error) => {
    console.log(error);
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    const code = res.data.code || 200;
    const msg = res.data.msg;

    if (code === 401) {
      // 如果已经在处理401，直接返回，避免重复处理
      if (isHandling401) {
        return res;
      }

      isHandling401 = true;
      MessageBox.confirm(
        "登录状态已过期，您可以继续操作，或者重新登录",
        "系统提示",
        {
          confirmButtonText: "重新登录",
          type: "warning",
        }
      )
        .then(() => {
          localStorage.removeItem("token");
          window.location.href = "/login";
        })
        .catch(() => {
          // 用户点击了取消或关闭了弹窗
        })
        .finally(() => {
          isHandling401 = false;
        });
      return res;
    } else if (code === 403) {
      Message({
        message: "没有权限，请联系管理员",
        type: "error",
        duration: 5 * 1000,
      });
      return res;
    } else if (code == 200) {
      return res.data;
    } else {
      return res.data;
    }
  },
  (error) => {
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message({
      message: message,
      dangerouslyUseHTMLString: true,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
